# Copyright (C) 2007 Samuel Abels, http://debain.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
from Token       import Token
from GrammarBody import GrammarBody

class Grammar(Token):
    def __init__(self, parser, parent):
        Token.__init__(self, 'Grammar', parser)
        self.parent  = parent
        self.varname = None
        self.body    = None
        self.inherit = None

        parser.expect(self, 'keyword', 'grammar')
        parser.expect(self, 'whitespace')

        type, token = parser.token()
        if type == 'varname':
            parser.next()
            self.varname = token
        elif type == 'open_function_call':
            parser.next()
            self.varname = token[:-1]
            inherit_name = parser.expect(self, 'varname')[1]
            self.inherit = parent.get(inherit_name).body
            parser.expect(self, 'close_bracket')
        else:
            parser.unexpected_token_error(self, parser.token())

        self.parent.define(**{self.varname: self})
        self.mark_end(parser)
        parser.expect(self, 'whitespace')

        parser.expect(self, 'open_curly_bracket')
        self.body = GrammarBody(parser, parent, self.inherit)
        parser.expect(self, 'close_curly_bracket')


    def dump(self, indent = 0):
        print (' ' * indent) + self.name, repr(self.input)
        self.body.dump(indent + 1)
